package com.jams.goodox.activity.login;

import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.home.HomeActivity;
import com.jams.goodox.activity.qa.GlideCircleTransform;
import com.jams.goodox.activity.qa.parent.UploadQuestionActivity;
import com.jams.goodox.net.ProtocolManagers;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.PhotoSelectUtils;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.ActionSheetDialog;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import cn.addapp.pickers.entity.City;
import cn.addapp.pickers.entity.County;
import cn.addapp.pickers.entity.Province;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by HP on 2018/5/8.
 * 注册第二步 填写用户相关信息
 *
 * api/member/update
 */

public class RoleInfoUploadActivity extends BaseActivity {

    private static final String TAG = "RoleInfoUploadActivity";
    private static final int CITY_CODE = 50;

    @Bind(R.id.nickName)
    EditText nickName;

    @Bind(R.id.submm_btn)
    TextView submm_btn;

    @Bind(R.id.headImage)
    ImageView headImage;

    private EditText individualitySign;//教师头衔


    private TextView city;//城市
    private TextView grade;//年级

    private ImageView certificates;//证件

    int type = 1;//用户类型（1家长，2教师）
    private boolean isTeacher = false;
    private Intent intent;
    private String cityLocation;
    private String studentGrade;

    //图片选择工具
    private PhotoSelectUtils mPhotoSelectUtils;
    private boolean certificatesUpload = true;
    private String headImagePath = "";

    @Override
    protected int getLayoutId() {
        type = getIntent().getIntExtra("type",1);
        isTeacher = type == 2 ? true : false;

        return isTeacher ? R.layout.activity_role_teacher : R.layout.activity_role_parent;
    }

    @Override
    protected void init() {
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_theme));//沉侵式头部
        StyleUtil.titleBackKey(this, "资料完善");

        if(isTeacher){
            submm_btn.setText("提交审核");
        }else {
            submm_btn.setText("确认");
        }

        if(isTeacher){
            individualitySign = (EditText) findViewById(R.id.individualitySign);
            certificates = (ImageView) findViewById(R.id.certificates);
            certificates.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //上传文件
                    certificatesUpload = true;
                    showPop();
                }
            });
        }else {
            city = (TextView) findViewById(R.id.city);
            grade = (TextView) findViewById(R.id.grade);

            city.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                   intent = new Intent(RoleInfoUploadActivity.this,CityPickerActivity.class);
                   startActivityForResult(intent,CITY_CODE);

                }
            });

            grade.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AddressPickTask task = new AddressPickTask(RoleInfoUploadActivity.this);
                    task.setHideCounty(true);
                    task.setCallback(new AddressPickTask.Callback() {
                        @Override
                        public void onAddressInitFailed() {
                            ToastUtil.show("数据初始化失败");
                        }

                        @Override
                        public void onAddressPicked(Province province, City city, County county) {
                            ToastUtil.show(province.getAreaName() + " " + city.getAreaName());
                            Log.d(TAG,province.getAreaName() + " " + city.getAreaName());
                            studentGrade = (/*province.getAreaName() + " " + */city.getAreaName());
                            grade.setText(studentGrade);

                        }
                    });
                    task.execute("a", "b");

                }
            });
        }
    }

    @OnClick({R.id.submm_btn,R.id.headImage})
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.submm_btn:
                updataMemberInfo();
                break;

            case R.id.headImage:
                certificatesUpload = false;
                showPop();
                break;
        }
    }

    private void updataMemberInfo() {
        if(TextUtils.isEmpty(nickName.getText())){
            ToastUtil.show("请填写用户昵称");
            return;
        }

        //用户头像
        if(TextUtils.isEmpty(headImagePath)){
            ToastUtil.show("请选择用户头像");
            return;
        }

        if(isTeacher){
            if(TextUtils.isEmpty(individualitySign.getText())){
                ToastUtil.show("请填写教师头衔");
                return;
            }

        }else {
            if(TextUtils.isEmpty(cityLocation)){
                ToastUtil.show("请选择地区");
                return;
            }

            if(TextUtils.isEmpty(studentGrade)){
                ToastUtil.show("请选择年级");
                return;
            }
        }

        Map<String,RequestBody> params = new HashMap<>();
        params.put("sign", RequestBody.create(MediaType.parse("multipart/form-data"), "test"));
        params.put("uuid", RequestBody.create(MediaType.parse("multipart/form-data"), "5617222222"));
        params.put("version", RequestBody.create(MediaType.parse("multipart/form-data"), "1.0"));
        params.put("accessToken", RequestBody.create(MediaType.parse("multipart/form-data"), SePref.getToken()));

        StringBuilder pData = new StringBuilder();
        pData.append("id:" + SePref.getId());
        pData.append(",gender:" + 1);

        pData.append(",memberType:" + (isTeacher? 2:1));
        pData.append(",nickName:" + nickName.getText());

        if(isTeacher){
            pData.append(",individualitySign:" + 1);

        }else {
            pData.append(",grade:" + studentGrade);
            pData.append(",city:" + cityLocation);
        }

        params.put("requestData", RequestBody.create(MediaType.parse("multipart/form-data"), "{" + pData.toString() + "}"));

        File file = new File(headImagePath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Part filePart = MultipartBody.Part.createFormData("files", file.getName(),
                requestFile);

        showLoading();
        // 执行请求
        Call<ResponseBody> call = createCallService(LoginService.class).updataMemberInfo(params,filePart);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "updataMemberInfo data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code") &&
                            "true".equals(jsonObject.getString("responseData"))){
                        //SePref.putToken("test");
                        intent = new Intent(RoleInfoUploadActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d("Upload error:", t.getMessage());
            }
        });

    }


    private void uploadFile(final String filename) {
        final File file = new File(filename);

        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Part filePart = MultipartBody.Part.createFormData("files", file.getName(),
                requestFile);

        Map<String,RequestBody> params = new HashMap<>();

        params.put("sign", RequestBody.create(MediaType.parse("multipart/form-data"), "test"));
        params.put("uuid", RequestBody.create(MediaType.parse("multipart/form-data"), "5617222222"));
        params.put("version", RequestBody.create(MediaType.parse("multipart/form-data"), "1.0"));
        params.put("accessToken", RequestBody.create(MediaType.parse("multipart/form-data"), SePref.getToken()));
        params.put("requestData", RequestBody.create(MediaType.parse("multipart/form-data"), "{id:" + SePref.getId() + "}"));

        showLoading();
        // 执行请求
        Call<ResponseBody> call = createCallService(LoginService.class).upload(params,filePart);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "uploadFile data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code") &&
                            "true".equals(jsonObject.getString("responseData"))){
                        ToastUtil.show("上传成功" );
                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"Upload error:" + t.getMessage());
            }
        });

    }


    private void showPop() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .addSheetItem("相机", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                checkPic(true);
                            }
                        })
                .addSheetItem("图库", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                checkPic(false);
                            }
                        }).show();
    }

    private void checkPic(boolean isCamera) {
        if(null == mPhotoSelectUtils){
            mPhotoSelectUtils = new PhotoSelectUtils(this);
            mPhotoSelectUtils.setTailor(1, 1, 350, 350);
        }

        if(isCamera){
            mPhotoSelectUtils.startTakeWayByCarema();
        }else {
            mPhotoSelectUtils.startTakeWayByAlbum();
        }

        mPhotoSelectUtils.setTakePictureCallBackListener(new PhotoSelectUtils.takePictureCallBackListener() {
            @Override
            public void successful(boolean isTailor, File outFile, Uri filePath) {
                Log.d(TAG,"filePath.getPath() = " + filePath.getPath());

                if(TextUtils.isEmpty(filePath.getPath())){
                    ToastUtil.show("图片选择失败，请重新选取");
                  return;
                }

                if(certificatesUpload){
                    //上传文件
                    uploadFile(filePath.getPath());

                }else {
                    headImagePath = filePath.getPath();
                    Glide.with(RoleInfoUploadActivity.this).load(filePath)
                            .placeholder(R.drawable.loading) //占位符 也就是加载中的图片，可放个gif
                            .error(R.mipmap.morentouxiang60) //失败图片
                            .bitmapTransform(new GlideCircleTransform(RoleInfoUploadActivity.this)).crossFade(1000).into(headImage);
                }
            }

            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {
                Log.d(TAG,"deniedPermissions = " + deniedPermissions);
            }

        });

    }


    //把本地的onActivityResult()方法回调绑定到对象
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(null != mPhotoSelectUtils) {
            mPhotoSelectUtils.attachToActivityForResult(requestCode, resultCode, data);
        }

        if(data != null && CITY_CODE == requestCode){
            cityLocation =  data.getStringExtra("city");
            city.setText(cityLocation);
          Log.d(TAG,"cityLocation = " + cityLocation);
        }

    }

    //onRequestPermissionsResult()方法权限回调绑定到对象
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPhotoSelectUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
